# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from dlgAttachments import *
import mimetypes
from metadataobject import *
from metadataObjectsModel import *
import os
import base64
import psycopg2

class DlgAttachmentsImpl (QDialog, Ui_dlgAttachments):
  def __init__(self, metaProcessor=None):
    QDialog.__init__(self)
    self.setupUi(self)
    self.btAdd.clicked.connect(self.btAddClicked)
    self.btDelete.clicked.connect(self.btDeleteClicked)
    self.btRefresh.clicked.connect(self.btRefreshClicked)
    self.metaProcessor = metaProcessor
    self.metadataObjectsModel = MetadataObjectsModel()
    self.tvAttachedFiles.setModel(self.metadataObjectsModel)
    self.tvAttachedFiles.setSelectionMode(QAbstractItemView.MultiSelection)

  def setConnectionString(self,conn_string):
    self.conn_string = conn_string

  def setMetaTableName(self,metaTableName):	
    self.metaTableName=metaTableName

  def setFeature(self,feature):	
    self.feature=feature
    self.loadObjectsFromDb()

  def btAddClicked(self, checked):
    print "btAddClicked"
    filename=str(QFileDialog.getOpenFileName(self, "Add attachment", "", "*.*" ).toUtf8())
    if None != filename and "" != filename:
      print filename
      metaObject = MetaDataObject()
      metaObject.tag="attachment" #make this constants
      metaObject.meta = os.path.basename(str(filename))
      metaObject.mimeType = mimetypes.guess_type(str(filename))[0]
      if None==metaObject.mimeType:
        metaObject.mimeType = "application/octet-stream"
      metaObject.filename = filename
      metaObject.state = MetaDataObject.STATE_INSERT
      self.metadataObjectsModel.beginResetModel()
      self.metadataObjectsModel.listdata.append(metaObject)
      self.metadataObjectsModel.endResetModel()

  def btDeleteClicked(self, checked):
    self.metadataObjectsModel.beginResetModel()
    for index in self.tvAttachedFiles.selectedIndexes():
      modelObject=index.model().listdata[index.row()]
      print modelObject.state
      modelObject.state = MetaDataObject.STATE_DELETE
    self.metadataObjectsModel.endResetModel()

  def btRefreshClicked(self, checked):
    self.loadObjectsFromDb()
  
  def done(self, state):
    if QDialog.Accepted==state:
      listToDel = []
      for metaDataObject in self.metadataObjectsModel.listdata:
        if MetaDataObject.STATE_INSERT==metaDataObject.state:
          self.insertNewDataToDb(metaDataObject)
        if MetaDataObject.STATE_DELETE == metaDataObject.state:
          listToDel.append(metaDataObject.ID)
      if len(listToDel)>0:
        self.deleteDataFromDb(listToDel)
    QDialog.done(self, state)

  def insertNewDataToDb(self, metaDataObj):
    sql="INSERT INTO " 
    sql+=self.metaTableName 
    sql+="(tag,mimetype,meta,data, fk_obj) VALUES(%(tag)s, %(mimetype)s, %(meta)s, %(data)s, %(fk_obj)s)"
    conn = psycopg2.connect(self.conn_string)
    curr = conn.cursor()
    curr.execute(sql,{"tag":metaDataObj.tag,
    "mimetype":metaDataObj.mimeType,
    "meta":metaDataObj.meta,
    "data":self.loadDataFromFile(metaDataObj.filename), 
    "fk_obj":self.feature.id()})
    conn.commit()
    curr.close()
    conn.close()
  
  def deleteDataFromDb(self, listIdsToDelete):
    sql= "delete from "
    sql+=self.metaTableName 
    sql+=' where mid in %(list_to_del)s'
    conn = psycopg2.connect(self.conn_string)
    curr = conn.cursor()
    curr.execute(sql,{"list_to_del":tuple(listIdsToDelete)})
    conn.commit()
    curr.close()
    conn.close()
  
  def loadObjectsFromDb(self):
    self.metadataObjectsModel.listdata = []
    self.metadataObjectsModel.beginResetModel()
    sql='SELECT mid, tag, meta, mimetype, data, fk_obj from ' 
    sql+=self.metaTableName 
    sql+=" where fk_obj=%(fk_obj)s and tag='attachment' "
    print self.conn_string
    conn = psycopg2.connect(self.conn_string)
    curr = conn.cursor()
    curr.execute(sql,{"fk_obj":self.feature.id()})
    result = curr.fetchone()
    while(None != result):
      metaObject = MetaDataObject()
      metaObject.ID = result[0]
      metaObject.tag = result[1]
      metaObject.meta = result[2]
      metaObject.mimeType = result[3]
      if metaObject.mimeType == None:
        metaObject.mimeType="application/octet-stream"
      metaObject.state = MetaDataObject.STATE_NOT_CHANGED
      self.metadataObjectsModel.listdata.append(metaObject)
      result = curr.fetchone()
    self.metadataObjectsModel.endResetModel()
    self.tvAttachedFiles.resizeColumnToContents(0)
    conn.commit()
    curr.close()
    conn.close()
  
  def loadDataFromFile(self,fileName):
    fileData = ""
    if fileName != None:
      fileHandle = file(fileName,'rb')
      fileData=base64.b64encode(fileHandle.read())
    return fileData
